//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package dao

import (
	"context"
	"encoding/json"
	"time"

	bg_runner_core "atomgit.com/openlinksaas-org/api-server/bg_runner/core"
	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type BgTaskDbItem struct {
	BgTaskId         string `bson:"_id"`
	BgTaskType       string `bson:"bgTaskType"`
	BgTaskData       string `bson:"bgTaskData"`
	TimeStamp        int64  `bson:"timeStamp"`
	VisibleTimeStamp int64  `bson:"visibleTimeStamp"`
}

type _BgTaskDao struct {
	mc *mongo.Collection
}

func newBgTaskDao(db *mongo.Database) (*_BgTaskDao, error) {
	mc := db.Collection(db_ns.DB_NS_GLOBAL + "bg_task")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"visibleTimeStamp", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_BgTaskDao{mc: mc}, nil
}

func (db *_BgTaskDao) Insert(ctx context.Context, bgTaskId string, nowTime, visibleTime int64, task bg_runner_core.BackGroundTask) error {
	taskData, err := json.Marshal(task)
	if err != nil {
		return err
	}
	dbItem := &BgTaskDbItem{
		BgTaskId:         bgTaskId,
		BgTaskType:       task.TaskType(),
		BgTaskData:       string(taskData),
		TimeStamp:        nowTime,
		VisibleTimeStamp: visibleTime,
	}
	_, err = db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_BgTaskDao) Exist(ctx context.Context, bgTaskId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": bgTaskId})
	return count > 0, err
}

func (db *_BgTaskDao) GetNextTask(ctx context.Context) (*BgTaskDbItem, error) {
	nowTime := time.Now().UnixNano() / 1e6
	retItem := &BgTaskDbItem{}
	err := db.mc.FindOneAndUpdate(ctx,
		bson.M{"visibleTimeStamp": bson.M{"$lte": nowTime}},
		bson.M{"$set": bson.M{"visibleTimeStamp": nowTime + 600*1000}}).Decode(retItem)
	return retItem, err
}

func (db *_BgTaskDao) RemoveTask(ctx context.Context, bgTaskId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": bgTaskId})
	return err
}
